package com.lxc.mapping;

import javax.servlet.*;
import com.lxc.common.MusicIdNum;
import javax.servlet.http.*;
import java.io.*;
import com.lxc.service.FileManagement;
import com.lxc.common.Music;
import com.lxc.service.MusicDatabase;

public class AddMusic{
    HttpServletRequest request;
    HttpServletResponse response;
    public AddMusic(HttpServletRequest request,HttpServletResponse response){
        this.request = request;
        this.response = response;
    }
    public void addMusic()throws IOException,ServletException{
		//设置接收的编码方式
		//request.setCharacterEncoding("UTF-8");
        Part partSinger = request.getPart("singer");
        Part partSongName = request.getPart("songname");
        Part partImage = request.getPart("image");
        Part partMusic = request.getPart("music");

        InputStream singerInput = partSinger.getInputStream();
        byte[] singerBytes = new byte[singerInput.available()];
        singerInput.read(singerBytes);
        String singerString = new String(singerBytes,"UTF-8");

        InputStream songNameInput = partSongName.getInputStream();
        byte[] songNameBytes = new byte[songNameInput.available()];
        songNameInput.read(songNameBytes);
        String songNameString = new String(songNameBytes,"UTF-8");

        String fileName = String.valueOf(MusicIdNum.getId());
        //image
        //partImage.write("../../../../../../resources/image/"+name+".jpg");//感觉要使用绝对路径好一点
        FileManagement fileManagement = new FileManagement();
		String imageAddress = fileManagement.saveFile(partImage,fileName,".jpg");

        //music
        //partMusic.write("../../../../../../resources/image/"+name+".mp3");//感觉要使用绝对路径好一点
        String musicAddress = fileManagement.saveFile(partMusic,fileName,".mp3");

        //数据库保存
        Music music = new Music();
        music.setSinger(singerString);
        music.setSongName(songNameString);
        music.setImageAddress(imageAddress);
        music.setMusicAddress(musicAddress);
		MusicDatabase musicDatabase = new MusicDatabase();
		musicDatabase.saveMusic(music);

    }

}